<template>
  <div class="container">
    <div class="container_left">
      <el-popover
        :disabled="lookState"
        placement="right-start"
        width="200"
        trigger="hover"
        popper-class="zx-popover"
      >
        <div class="topic_type">
          <div @click="addBigTitle(1)" class="topic_item">
            <i class="el-icon-postcard">
              固定试卷大题
              <el-tooltip
                class="item"
                effect="dark"
                placement="top-start"
                :open-delay="300"
              >
                <div slot="content">
                  提示：<br />添加试题组成大题。（每位考生该部分试题内容相同）
                </div>
                <i class="el-icon-question"></i>
              </el-tooltip>
            </i>
          </div>
          <div
            @click="addBigTitle(2)"
            class="topic_item"
            v-if="operationType !== 5 && operationType !== 6"
          >
            <i class="el-icon-refresh">
              抽题试卷大题
              <el-tooltip
                class="item"
                effect="dark"
                placement="top-start"
                :open-delay="300"
              >
                <div slot="content">
                  提示：<br />1、点击【添加抽题容器】，再点击【抽题管理】，添加试题；<br />2、设置抽题规则和数量；<br />3、系统根据设定的规则，从抽题容器中随机抽取指定数量的试题生成大题。（每位考生该部分试题内容会不同）
                </div>
                <i class="el-icon-question"></i>
              </el-tooltip>
            </i>
          </div>
          <div
            @click="addBigTitle(3)"
            class="topic_item"
            v-if="operationType !== 5 && operationType !== 6"
          >
            <i class="el-icon-connection">
              随机试卷大题
              <el-tooltip
                class="item"
                effect="dark"
                placement="top-start"
                :open-delay="300"
              >
                <div slot="content">
                  提示：<br />1、点击【随机策略】，选择题型和知识点；<br />
                  2、设置抽题规则和数量；<br />
                  3、系统根据设定的规则，随机自动抽取指定数量的试题生成大题。（每位考生该部分试题内容会不同）
                </div>
                <i class="el-icon-question"></i>
              </el-tooltip>
            </i>
          </div>
        </div>
        <el-button slot="reference" class="add_topic_btn">
          添加试卷大题<i class="el-icon-caret-right"></i>
        </el-button>
      </el-popover>
      <div class="title_total">
        共 <span>{{ totalTopicNum }}</span> 题 <span>{{ totalScore }}</span> 分
      </div>
      <div class="title_card">
        <div
          class="box_card"
          v-for="(bigTitle, index) in topicLabelList"
          :key="bigTitle.id"
        >
          <div class="clearfix">
            <span v-if="!bigTitle.showTitleEdit">
              <span
                @click="scrollToAnchor(`bigTitle-${bigTitle.id}`)"
                style="
                  text-overflow: ellipsis;
                  white-space: nowrap;
                  overflow: hidden;
                  max-width: 90px;
                  font-size: 16px;
                  cursor: pointer;
                  user-select: none;
                "
              >
                {{ bigTitle.title ? bigTitle.title : `第${index + 1}大题` }}
              </span>
              <el-button
                :disabled="lookState"
                v-preventReClick
                type="text"
                icon="el-icon-edit-outline"
                style="margin-left: 5px"
                @click="showTitleEditDiv(bigTitle)"
              />
            </span>
            <span v-else>
              <el-input
                :disabled="lookState"
                v-model="bigTitle.title"
                :ref="'titleEdit' + bigTitle.id"
                size="mini"
                style="width: 150px"
                @blur="changeTitleName(bigTitle, 'left')"
                @keyup.enter="changeTitleName(bigTitle, 'left')"
              />
            </span>
            <span style="font-size: 12px; color: #949494; margin-left: 6px"
              >(共{{ bigTitle.topicNum }}题{{ bigTitle.score }}分)</span
            >
            <!-- 删除  -->
            <el-popover
              :disabled="lookState"
              placement="top-end"
              width="160"
              v-model="bigTitle.delState"
            >
              <div
                style="
                  text-align: center;
                  width: 100%;
                  padding: 10px;
                  box-sizing: border-box;
                "
              >
                <p>确定要删除吗？</p>
                <div style="display: flex; width: 100%; margin-top: 8px">
                  <el-button
                    v-preventReClick
                    size="mini"
                    @click="bigTitle.delState = false"
                    >取消</el-button
                  >
                  <el-button
                    v-preventReClick
                    type="primary"
                    size="mini"
                    @click="delBigTitle(bigTitle, index)"
                    >确定</el-button
                  >
                </div>
              </div>
              <el-button
                :disabled="lookState"
                v-preventReClick
                style="float: right; margin: 0"
                type="text"
                icon="el-icon-delete"
                slot="reference"
              ></el-button>
            </el-popover>
            <!-- 编辑  -->
            <el-popover
              :disabled="lookState"
              placement="top-end"
              width="160"
              v-model="bigTitle.edit"
              @show="editAvgScore(bigTitle.id)"
            >
              <div
                style="
                  text-align: center;
                  width: 100%;
                  padding: 10px;
                  box-sizing: border-box;
                "
              >
                <el-input
                  :disabled="lookState"
                  v-model="bigTitle.avgScore"
                  oninput="value=value.replace(/^0|[^0-9]/g,'')"
                  size="small"
                  style="width: 80%; margin-bottom: 5px"
                  :ref="'avgScoreVal$' + bigTitle.id"
                ></el-input>
                分<br />
                <div style="display: flex; width: 100%; margin-top: 8px">
                  <el-button
                    v-preventReClick
                    size="mini"
                    @click="bigTitle.edit = false"
                    >取消</el-button
                  >
                  <el-button
                    v-preventReClick
                    size="mini"
                    type="primary"
                    @click="setScore(bigTitle)"
                    >确定</el-button
                  >
                </div>
              </div>
              <el-button
                :disabled="lookState"
                v-preventReClick
                style="float: right; margin: 0"
                type="text"
                icon="el-icon-edit"
                slot="reference"
                >每题配分</el-button
              >
            </el-popover>
            <!-- 下移  -->
            <el-tooltip
              class="item"
              effect="dark"
              content="下移"
              placement="top-end"
              :open-delay="1000"
            >
              <el-button
                :disabled="lookState"
                v-preventReClick
                style="float: right; margin: 0"
                type="text"
                icon="el-icon-download"
                v-if="bigTitle.sort != topicLabelList.length"
                @click="moveTitle(bigTitle.id, bigTitle.sort, 1)"
              ></el-button>
            </el-tooltip>
            <!-- 上移  -->
            <el-tooltip
              class="item"
              effect="dark"
              content="上移"
              placement="top-end"
              :open-delay="1000"
            >
              <el-button
                :disabled="lookState"
                v-preventReClick
                style="float: right; margin: 0"
                type="text"
                icon="el-icon-upload2"
                v-if="bigTitle.sort != 1"
                @click="moveTitle(bigTitle.id, bigTitle.sort, -1)"
              ></el-button>
            </el-tooltip>
          </div>
          <div class="topicBox">
            <div
              class="label_index"
              @click="scrollToAnchor(label.id)"
              v-for="(label, index) in bigTitle.labelList"
              :key="label.index"
            >
              {{ index + 1 }}
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="container_right">
      <el-card
        v-for="(bigTitle, index) in form.titleList"
        :key="bigTitle.id"
        ref="bigTitleCard"
      >
        <div slot="header" class="clearfix">
          <span v-if="!bigTitle.showTitleEdit">
            <span
              :id="'bigTitle-' + bigTitle.id"
              style="
                text-overflow: ellipsis;
                white-space: nowrap;
                overflow: hidden;
                max-width: 90px;
                font-size: 18px;
                margin: 15px 5px 3px 5px;
              "
            >
              {{ bigTitle.title ? bigTitle.title : `第${index + 1}大题` }}
              <!-- 第{{
                index + 1
              }}大题 -->
            </span>
            <el-button
              :disabled="lookState"
              v-preventReClick
              type="text"
              icon="el-icon-edit-outline"
              style="margin-left: 5px"
              @click="showTitleEditDiv(bigTitle)"
            />
          </span>
          <span v-else>
            <el-input
              :disabled="lookState"
              v-model="bigTitle.title"
              :ref="'titleEdit' + bigTitle.id"
              style="width: 150px"
              @blur="changeTitleName(bigTitle)"
              @keyup.enter="changeTitleName(bigTitle)"
            />
          </span>
          <span style="font-size: 12px; color: #949494; margin-left: 6px"
            >(共{{ bigTitle.topicNum }}题{{ bigTitle.score }}分)</span
          >
          <el-checkbox
            :disabled="lookState"
            style="float: right; margin: 0"
            border
            v-model="bigTitle.optionUnsort"
            @change="optionUnsortChange(bigTitle)"
            >选项乱序
          </el-checkbox>
          <el-checkbox
            :disabled="lookState"
            style="float: right; margin: 0"
            border
            v-if="bigTitle.type === 1"
            v-model="bigTitle.topicUnsort"
            @change="topicUnsortChange(bigTitle)"
            >试题乱序
          </el-checkbox>
        </div>
        <!-- TAG:固定大题编辑窗口 -->
        <div v-if="bigTitle.type === 1">
          <el-table :data="bigTitle.topicList">
            <el-table-column prop="index" label="序号" min-width="3%">
              <template slot-scope="scope">
                <span :id="'topic-' + scope.row.id">{{
                  scope.$index + 1
                }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="topicType" label="题型" min-width="5%">
              <template slot-scope="scope">
                <span>{{ returnTopicType(scope.row.topicType) }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="content"
              label="题干"
              min-width="25%"
              :show-overflow-tooltip="true"
            />
            <el-table-column大题
              prop="answer"
              label="答案"
              min-width="15%"
              :show-overflow-tooltip="true"
            />
            <el-table-column prop="difficulty" label="难度" min-width="5%">
              <template slot-scope="scope">
                <span>{{ returnDifficulty(scope.row.difficulty) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="score" label="分值" min-width="5%">
              <template slot-scope="scope">
                <el-input
                  :disabled="lookState"
                  oninput="value=value.replace(/^0|[^0-9]/g,'')"
                  v-model.trim="scope.row.score"
                  size="mini"
                  style="width: 75px; padding: 0px"
                  @change="
                    changeTopicScore(
                      scope.row.id,
                      scope.row.titleId,
                      scope.row.score
                    )
                  "
                />
              </template>
            </el-table-column>
            <el-table-column prop="operate" label="操作" min-width="5%">
              <template slot-scope="scope">
                <el-button
                  :disabled="lookState"
                  v-preventReClick
                  type="text"
                  size="small"
                  icon="el-icon-edit-outline"
                  @click.native.stop="
                    showTopicEditDialog(scope.row.id, bigTitle.id)
                  "
                  style="margin-right: 5px"
                />
                <el-button
                  :disabled="lookState"
                  @click="delPaperTopic(scope.row.id, bigTitle.id)"
                  v-preventReClick
                  type="text"
                  size="small"
                  icon="el-icon-delete"
                  slot="reference"
                />
              </template>
            </el-table-column>
          </el-table>
          <el-button
            :disabled="lookState"
            v-preventReClick
            type="primary"
            icon="el-icon-plus"
            style="margin: 5px"
            @click.native.stop="showTopicEditDialog(0, bigTitle.id)"
            >添加试题
          </el-button>
          <el-button
            :disabled="lookState"
            v-preventReClick
            type="primary"
            icon="el-icon-plus"
            style="margin: 5px"
            @click.native.stop="showTopicListDialog(bigTitle.id, operationType)"
            >从试题库选择
          </el-button>
        </div>
        <!-- TAG:抽题大题编辑窗口 -->
        <div v-else-if="bigTitle.type === 2">
          <el-table :data="bigTitle.containerList">
            <el-table-column prop="index" label="序号" min-width="3%">
              <template slot-scope="scope">
                <span>{{ scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="container" label="抽题容器" min-width="20%">
              <template slot-scope="scope">
                <el-button
                  :id="'container-' + scope.row.id"
                  :disabled="lookState"
                  v-preventReClick
                  type="primary"
                  icon="el-icon-s-management"
                  style="margin: 5px"
                  plain
                  @click.native.stop="
                    showContainerEditDialog(scope.row.id, bigTitle.id)
                  "
                >
                  抽题管理（{{ scope.row.totalNum }}）
                </el-button>
              </template>
            </el-table-column>
            <el-table-column
              prop="unlimitedNum"
              label="不限难度"
              min-width="8%"
            >
              <template slot-scope="scope">
                <el-input
                  :disabled="lookState"
                  v-model.number="scope.row.unlimitedNum"
                  size="mini"
                  style="width: 50px"
                  @blur="containerUnlimitedNumChange(scope.row)"
                />
                /
                <span>{{ scope.row.optionalUnlimitedNum }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="easyNum" label="容易" min-width="8%">
              <template slot-scope="scope">
                <el-input
                  :disabled="lookState"
                  v-model.number="scope.row.easyNum"
                  size="mini"
                  style="width: 50px"
                  @blur="containerEasyNumChange(scope.row)"
                />
                /
                <span>{{ scope.row.optionalEasyNum }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="normalNum" label="中等" min-width="8%">
              <template slot-scope="scope">
                <el-input
                  :disabled="lookState"
                  v-model.number="scope.row.normalNum"
                  size="mini"
                  style="width: 50px"
                  @blur="containerNormalNumChange(scope.row)"
                />
                /
                <span>{{ scope.row.optionalNormalNum }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="hardNum" label="困难" min-width="8%">
              <template slot-scope="scope">
                <el-input
                  :disabled="lookState"
                  v-model.number="scope.row.hardNum"
                  size="mini"
                  style="width: 50px"
                  @blur="containerHardNumChange(scope.row)"
                />
                /
                <span>{{ scope.row.optionalHardNum }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="extractNum" label="抽题数" min-width="5%" />
            <el-table-column prop="score" label="每题分数" min-width="5%">
              <template slot-scope="scope">
                <el-input
                  :disabled="lookState"
                  oninput="value=value.replace(/^0|[^0-9]/g,'')"
                  v-model.trim="scope.row.score"
                  size="mini"
                  style="width: 75px; padding: 0px"
                  @change="containerScoreChange(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="operate" label="操作" min-width="4%">
              <template slot-scope="scope">
                <el-button
                  :disabled="lookState"
                  v-preventReClick
                  type="text"
                  size="small"
                  icon="el-icon-delete"
                  @click="delContainer(bigTitle.id, scope.row.id)"
                />
              </template>
            </el-table-column>
          </el-table>
          <el-button
            :disabled="lookState"
            v-preventReClick
            type="primary"
            icon="el-icon-plus"
            style="margin: 5px"
            @click.native.stop="addContainer(bigTitle.id)"
            >添加抽题容器
          </el-button>
        </div>
        <!-- TAG:随机大题编辑窗口 -->
        <div v-else>
          <el-table :data="bigTitle.tacticsList">
            <el-table-column prop="index" label="序号" min-width="3%">
              <template slot-scope="scope">
                <span>{{ scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="topicType" label="题型" min-width="8%">
              <template slot-scope="scope">
                <el-select
                  v-if="!isOfflineExam"
                  :disabled="lookState"
                  :class="{ error_border: !(scope.row.topicType + '') }"
                  v-model="scope.row.topicType"
                  placeholder="请选择题型"
                  @change="updateTacticsInfo(scope.row)"
                >
                  <el-option
                    v-for="dict in dict.type.topic_type"
                    :key="Number(dict.value)"
                    :label="dict.label"
                    :value="Number(dict.value)"
                  />
                </el-select>
                <el-select
                  v-if="isOfflineExam"
                  :disabled="lookState"
                  :class="{ error_border: !(scope.row.topicType + '') }"
                  v-model="scope.row.topicType"
                  placeholder="请选择题型"
                  @change="updateTacticsInfo(scope.row)"
                >
                  <el-option
                    v-if="dict.value == 5"
                    v-for="dict in dict.type.topic_type"
                    :key="Number(dict.value)"
                    :label="dict.label"
                    :value="Number(dict.value)"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="categoryId" label="知识点" min-width="12%">
              <template slot-scope="scope">
                <div style="display: flex; align-items: center">
                  <el-cascader
                    :disabled="lookState"
                    :class="{ errors_border: !(scope.row.categoryId + '') }"
                    v-model="scope.row.categoryId"
                    :options="topicCategoryTree"
                    filterable
                    :props="{ expandTrigger: 'hover', checkStrictly: true }"
                    @change="topicCategoryChange(scope.row)"
                  />
                  <el-link
                    :disabled="lookState"
                    @click="lookInfo(scope.row.id, scope.row)"
                    type="primary"
                    style="margin-left: 6px"
                    :underline="false"
                    >查看
                  </el-link>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="unlimitedNum"
              label="不限难度"
              min-width="5%"
            >
              <template slot-scope="scope">
                <el-input
                  :disabled="lookState"
                  v-model.number="scope.row.unlimitedNum"
                  size="mini"
                  style="width: 50px"
                  @blur="tacticsUnlimitedNumChange(scope.row)"
                />
                /
                <span>{{ scope.row.optionalUnlimitedNum }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="easyNum" label="容易" min-width="5%">
              <template slot-scope="scope">
                <el-input
                  :disabled="lookState"
                  v-model.number="scope.row.easyNum"
                  size="mini"
                  style="width: 50px"
                  @blur="tacticsEasyNumChange(scope.row)"
                />
                /
                <span>{{ scope.row.optionalEasyNum }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="normalNum" label="中等" min-width="5%">
              <template slot-scope="scope">
                <el-input
                  :disabled="lookState"
                  v-model.number="scope.row.normalNum"
                  size="mini"
                  style="width: 50px"
                  @blur="tacticsNormalNumChange(scope.row)"
                />
                /
                <span>{{ scope.row.optionalNormalNum }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="hardNum" label="困难" min-width="5%">
              <template slot-scope="scope">
                <el-input
                  :disabled="lookState"
                  v-model.number="scope.row.hardNum"
                  size="mini"
                  style="width: 50px"
                  @blur="tacticsHardNumChange(scope.row)"
                />
                /
                <span>{{ scope.row.optionalHardNum }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="extractNum" label="抽题数" min-width="5%" />
            <el-table-column prop="score" label="每题分数" min-width="5%">
              <template slot-scope="scope">
                <el-input
                  :id="'tactics-' + scope.row.id"
                  :disabled="lookState"
                  oninput="value=value.replace(/^0|[^0-9]/g,'')"
                  v-model.trim="scope.row.score"
                  size="mini"
                  style="width: 75px; padding: 0px"
                  @change="tacticsScoreChange(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="operate" label="操作" min-width="4%">
              <template slot-scope="scope">
                <el-button
                  :disabled="lookState"
                  v-preventReClick
                  type="text"
                  size="small"
                  icon="el-icon-delete"
                  @click="delTactics(bigTitle.id, scope.row.id)"
                />
              </template>
            </el-table-column>
          </el-table>
          <el-button
            :disabled="lookState"
            v-preventReClick
            type="primary"
            icon="el-icon-plus"
            style="margin: 5px"
            @click.native.stop="addTactics(bigTitle.id)"
            >添加随机策略
          </el-button>
        </div>
      </el-card>
    </div>
    <!-- 添加或修改试题对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="随机策略试题列表"
      :visible.sync="showTacticsTopic"
      width="1200px"
      append-to-body
    >
      <TopicInfoList ref="topicinfolist"></TopicInfoList>
    </el-dialog>
    <!-- 勾选添加试题对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="选择试题"
      :visible.sync="form.showTopicList"
      width="1200px"
      append-to-body
    >
      <div class="topicListDiv">
        <TopicList
          :parentopen="form.showTopicList"
          :taskId="taskld"
          ref="myTopicList"
          :isOfflineExam="isOfflineExam"
          :propsCategoryId="topicCategoryId"
          :hiddenEdit="true"
          @handleSelect="handleAddTopics"
        />
      </div>
      <div
        style="width: 100%; display: flex; justify-content: center"
        slot="footer"
      >
        <el-button v-preventReClick @click="form.showTopicList = false">
          关 闭
        </el-button>
      </div>
    </el-dialog>
    <!-- 抽题容器编辑页面-->
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="form.containerEditTitle"
      :visible.sync="form.showContainerEdit"
      width="70vw"
      append-to-body
      @close="closeContainerDialog"
    >
      <div class="topicListDiv">
        <ContainerEdit
          :taskId="taskld"
          :isOfflineExam="isOfflineExam"
          :propsId="topicCategoryId"
          ref="myContainerEdit"
          @handleClose="containerEditClose"
        />
      </div>
    </el-dialog>
    <!-- 添加或修改试题对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="form.topicEditTitle"
      :visible.sync="form.showTopicEdit"
      width="1200px"
      append-to-body
    >
      <TopicForm
        :operationType="operationType"
        @cancel="topicEditCancel"
        :isOfflineExam="isOfflineExam"
        :propsCategoryId="topicCategoryId"
        ref="myTopicForm"
        @handleClose="topicEditClose"
      />
    </el-dialog>
  </div>
</template>

<script>
import TopicInfoList from "./TopicInfoList";
import { getTopicCategoryTree } from "@/api/exam/topicCategory";
import {
  changeTopicScore,
  delExamPaperTopic,
  getPaperTopic,
  choiceTopic,
} from "@/api/exam/examPaperTopic";
import {
  addTactics,
  delTactics,
  updateTacticsUnlimitedNum,
  updateTacticsEasyNum,
  updateTacticsNormalNum,
  updateTacticsHardNum,
  updateTacticsScore,
  getTacticsByTitleId,
  updateTacticsInfo,
} from "@/api/exam/examPaperTactics";
import {
  addContainer,
  delContainer,
  getContainerById,
  updateContainerUnlimitedNum,
  updateContainerEasyNum,
  updateContainerNormalNum,
  updateContainerHardNum,
  updateContainerScore,
} from "@/api/exam/examPaperContainer";
import {
  addPaperTitle,
  sortPaperTitle,
  removePaperTitle,
  getPaperByExamId,
  setTitleAvgScore,
  changeOptionUnsort,
  changeTopicUnsort,
  editTitleName,
} from "@/api/exam/paper";
import TopicForm from "./TopicForm";
import TopicList from "./TopicList";
import ContainerEdit from "./ContainerEdit";

export default {
  name: "PaperEdit",
  dicts: ["topic_type", "topic_difficulty"],
  props: {
    operationType: {
      type: [String, Number],
      required: false,
    },
    examDialogOpen: {
      type: Boolean,
      default: false,
    },
    examId: {
      type: Number,
      required: false,
    },
    isOfflineExam: {
      type: Boolean,
      required: true,
    },
    lookState: {
      type: Boolean,
      required: false,
    },
    taskld: {
      type: Number,
      required: false,
    },
    topicCategoryId: {
      required: false,
    },
  },
  components: {
    TopicForm,
    TopicList,
    ContainerEdit,
    TopicInfoList,
  },
  data() {
    return {
      totalTopicNum: 0,
      totalScore: 0,
      //试题锚点
      topicLabelList: [],
      //知识点树
      topicCategoryTree: [],
      //默认选项
      defaultProps: {
        children: "children",
        label: "label",
      },
      form: {
        paper: {},
        titleList: [],
        topicEditTitle: "试题编辑",
        containerEditTitle: "抽题容器编辑",
        // 显示试题编辑页面
        showTopicEdit: false,
        showTopicList: false,
        showContainerEdit: false,
      },
      openContainerId: 0,
      showTacticsTopic: false,
      propsCategoryId: null,
    };
  },
  created() {},
  methods: {
    checkScore() {
      console.log(this.form.titleList, "this.form.titleList");
      let bool = true;
      if (this.form.titleList.length < 1) {
        this.$modal.msgWarning(`请先完成试卷设计，不能发布空卷`);
        bool = false;
        return;
      }
      for (const titleItem of this.form.titleList) {
        if (titleItem.topicList && titleItem.topicList.length > 0) {
          for (const [
            index,
            topicListElement,
          ] of titleItem.topicList.entries()) {
            if (topicListElement.score <= 0) {
              this.$modal.msgWarning(
                `题目分数必须大于0，请检查【${titleItem.title}、第${
                  index + 1
                }题】的分数`
              );
              let id = `topic-${topicListElement.id}`;
              const anchor = document.getElementById(id);
              if (anchor) {
                anchor.scrollIntoView({ behavior: "smooth" });
              }
              bool = false;
              return;
            }
          }
        }
        if (titleItem.containerList && titleItem.containerList.length > 0) {
          for (const [
            index,
            containerElement,
          ] of titleItem.containerList.entries()) {
            if (containerElement.score <= 0) {
              this.$modal.msgWarning(
                `题目分数必须大于0，请检查【${titleItem.title}、第${
                  index + 1
                }题】的分数`
              );
              let id = `container-${containerElement.id}`;
              const anchor = document.getElementById(id);
              if (anchor) {
                anchor.scrollIntoView({ behavior: "smooth" });
              }
              bool = false;
              return;
            }
          }
        }
        if (titleItem.tacticsList && titleItem.tacticsList.length > 0) {
          for (const [
            index,
            tacticsListElement,
          ] of titleItem.tacticsList.entries()) {
            if (tacticsListElement.score <= 0) {
              this.$modal.msgWarning(
                `题目分数必须大于0，请检查【${titleItem.title}、第${
                  index + 1
                }题】的分数`
              );
              let id = `tactics-${tacticsListElement.id}`;
              const anchor = document.getElementById(id);
              if (anchor) {
                anchor.scrollIntoView({ behavior: "smooth" });
              }
              bool = false;
              return;
            }
          }
        }
        if (titleItem.type == 1) {
          if (!titleItem.topicList || titleItem.topicList.length < 1) {
            this.$modal.msgWarning(
              `【${titleItem.title}】的题目数量为空，请添加题目`
            );
            let id = `bigTitle-${titleItem.id}`;
            const anchor = document.getElementById(id);
            if (anchor) {
              anchor.scrollIntoView({ behavior: "smooth" });
            }
            bool = false;
            return;
          }
        }
        if (titleItem.type == 2) {
          if (!titleItem.containerList || titleItem.containerList.length < 1) {
            this.$modal.msgWarning(
              `【${titleItem.title}】没有添加抽题容器，请添加抽题容器`
            );
            let id = `bigTitle-${titleItem.id}`;
            const anchor = document.getElementById(id);
            if (anchor) {
              anchor.scrollIntoView({ behavior: "smooth" });
            }
            bool = false;
            return;
          }
          for (const [
            index,
            containerElement,
          ] of titleItem.containerList.entries()) {
            if (containerElement.totalNum == 0) {
              this.$modal.msgWarning(
                `抽题容器的题目数量必须大于0，请检查【${titleItem.title}、第${
                  index + 1
                }题】的抽题容器题目数量`
              );
              let id = `container-${containerElement.id}`;
              const anchor = document.getElementById(id);
              if (anchor) {
                anchor.scrollIntoView({ behavior: "smooth" });
              }
              bool = false;
              return;
            }
          }
        }
        if (titleItem.type == 3) {
          if (!titleItem.tacticsList || titleItem.tacticsList.length < 1) {
            this.$modal.msgWarning(
              `【${titleItem.title}】没有添加随机策略，请添加随机策略`
            );
            let id = `bigTitle-${titleItem.id}`;
            const anchor = document.getElementById(id);
            if (anchor) {
              anchor.scrollIntoView({ behavior: "smooth" });
            }
            bool = false;
            return;
          }
        }
      }
      return bool;
    },
    getTotalScore() {
      console.log("获取总分");
      let totalScore = 0;
      for (const titleItem of this.form.titleList) {
        // 计算总分
        if (titleItem.topicList && titleItem.topicList.length > 0) {
          for (const topicListElement of titleItem.topicList) {
            if (topicListElement.score > 0) {
              totalScore += topicListElement.score - 0;
            }
          }
        }
        if (titleItem.containerList && titleItem.containerList.length > 0) {
          for (const containerElement of titleItem.containerList) {
            if (containerElement.score > 0) {
              totalScore += containerElement.score - 0;
            }
          }
        }
        if (titleItem.tacticsList && titleItem.tacticsList.length > 0) {
          for (const tacticsListElement of titleItem.tacticsList) {
            if (tacticsListElement.score > 0) {
              totalScore += tacticsListElement.score - 0;
            }
          }
        }
      }
      return totalScore;
    },
    //锚点跳转
    scrollToAnchor(id) {
      const anchor = document.getElementById(id);
      if (anchor) {
        anchor.scrollIntoView({ behavior: "smooth" });
      }
    },
    //查看题目详情
    lookInfo(id, row) {
      if (!row.categoryId || row.categoryId.length == 0) {
        this.$message.warning({ message: "请选择知识点", showClose: true });
        return;
      }
      this.showTacticsTopic = true;
      this.$nextTick(() => {
        this.$refs.topicinfolist.getList(id);
      });
    },
    //显示修改答题标题的输入框
    showTitleEditDiv(title) {
      this.$set(title, "showTitleEdit", true);
      this.$nextTick(() => {
        this.$refs["titleEdit" + title.id][0].focus();
      });
    },
    //修改大题标题
    changeTitleName(title, type) {
      if (type == "left") {
        for (const titleListElement of this.form.titleList) {
          if (titleListElement.id == title.id) {
            titleListElement.title == title.title;
            this.$set(titleListElement, "title", title.title);
          }
        }
      }
      editTitleName(title.id, title.title).then((res) => {
        if (res.code != 200) {
          this.$message.error({
            message: res.message,
            showClose: true,
          });
        }
      });
      this.$set(title, "showTitleEdit", false);
    },
    //修改选项乱序
    optionUnsortChange(bigTitle) {
      changeOptionUnsort(bigTitle.id, bigTitle.optionUnsort).then((res) => {
        if (res.code != 200) {
          this.$message.error({
            message: res.msg,
            showClose: true,
          });
        }
      });
    },
    //修改试题乱序
    topicUnsortChange(bigTitle) {
      changeTopicUnsort(bigTitle.id, bigTitle.topicUnsort).then((res) => {
        if (res.code != 200) {
          this.$message.error({
            message: res.msg,
            showClose: true,
          });
        }
      });
    },
    //添加随机策略
    addTactics(bigTitleId) {
      addTactics(this.form.paper.id, bigTitleId).then((res) => {
        console.log(res.data, "data");
        this.form.titleList.forEach((title) => {
          if (title.id == bigTitleId) {
            let obj = {
              ...res.data,
              categoryId: this.topicCategoryId,
            };
            title.tacticsList.push(obj);
          }
        });
      });
    },
    //删除随机策略
    delTactics(titleId, tacticsId) {
      if (tacticsId == null || tacticsId == undefined) {
        return;
      }
      this.$confirm("确认要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delTactics(tacticsId).then((res) => {
            this.$modal.msgSuccess("删除成功");
            this.form.titleList.forEach((title) => {
              if (title.id == titleId) {
                title.tacticsList.forEach((tactics) => {
                  if (tactics.id == tacticsId) {
                    let index = title.tacticsList.indexOf(tactics);
                    title.tacticsList.splice(index, 1);
                  }
                });
              }
            });
          });
        })
        .catch(() => {});
    },
    //添加抽题容器
    addContainer(bigTitleId) {
      addContainer(this.form.paper.id, bigTitleId).then((res) => {
        this.form.titleList.forEach((title) => {
          if (title.id == bigTitleId) {
            title.containerList.push(res.data);
          }
        });
      });
    },
    //删除抽题容器
    delContainer(titleId, containerId) {
      this.$confirm("确认要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delContainer(containerId).then((res) => {
            this.$modal.msgSuccess("删除成功");
            this.form.titleList.forEach((title) => {
              if (title.id == titleId) {
                title.containerList.forEach((container) => {
                  if (container.id == containerId) {
                    let index = title.containerList.indexOf(container);
                    title.containerList.splice(index, 1);
                  }
                });
              }
            });
          });
        })
        .catch(() => {});
    },
    //关闭抽题容器编辑页面
    containerEditClose() {
      this.form.showContainerEdit = false;
    },
    //获取试卷信息
    resetPaperInfo(examId) {
      if (examId == null || examId == undefined || examId == 0) {
        return;
      } else {
        getPaperByExamId(examId).then((res) => {
          let titles = res.data.titleList;
          titles.forEach((title) => {
            this.$set(title, "showTitleEdit", false);
          });
          this.$set(this.form, "paper", res.data.paper);
          this.$set(this.form, "titleList", titles);
          this.$nextTick(() => {
            this.sortTitleList();
            this.$set(this.form, "topicEditTitle", "试题编辑");
            this.$set(this.form, "containerEditTitle", "抽题容器编辑");
            this.$set(this.form, "showTopicEdit", false);
            this.$set(this.form, "showTopicList", false);
            this.$set(this.form, "showContainerEdit", false);
            this.$set(this.form, "showContainerList", false);
          });
        });
      }
    },
    //从题库勾选添加试题
    handleAddTopics(topicIds, titleId, containerId, loading) {
      choiceTopic(titleId, topicIds)
        .then((res) => {
          if (loading) {
            loading.close();
          }
          this.$modal.msgSuccess("添加成功");
          this.form.titleList.forEach((title) => {
            if (title.id === titleId) {
              title.topicList = title.topicList.concat(res.data.ccTopicList);
              title.topicNum = title.topicList.length;
              //试题列表累加分数计算大题分数
              title.score = title.topicList.reduce((total, topic) => {
                return total + topic.score;
              }, 0);
            }
            //更新随机策略信息
            if (res.data.ccPaperTacticsList.length > 0) {
              this.$set(
                title,
                "tacticsList",
                res.data.ccPaperTacticsList.filter(
                  (tactics) => tactics.titleId === title.id
                )
              );
            }
            //更新抽题容器信息
            if (
              res.data.ccPaperContainerList.length > 0 &&
              title.containerList &&
              title.containerList.length > 0
            ) {
              title.containerList.forEach((container, index) => {
                res.data.ccPaperContainerList.find((ccContainer) => {
                  if (ccContainer.id === container.id) {
                    title.containerList.splice(index, 1, ccContainer);
                  }
                });
              });
            }
          });
          this.$refs.myTopicList.loadTopicList(titleId, 0);
          // this.form.showTopicList = false;
          this.$nextTick(() => {
            this.sortTitleList();
          });
        })
        .catch((error) => {
          if (loading) {
            loading.close();
          }
        });
    },
    //删除试题
    delPaperTopic(topicId, titleId) {
      this.$confirm("确认要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delExamPaperTopic(topicId, titleId).then((res) => {
            this.$modal.msgSuccess("删除成功");
            this.form.titleList.forEach((title) => {
              if (title.id === titleId) {
                title.topicList.splice(
                  title.topicList.findIndex((topic) => topic.id === topicId),
                  1
                );
                title.topicNum = title.topicList.length;
                //试题列表累加分数计算大题分数
                title.score = title.topicList.reduce((total, topic) => {
                  return total + topic.score;
                }, 0);
              }
            });
            this.updateTacticsByTitleId(titleId);
            this.$nextTick(() => {
              this.sortTitleList();
            });
          });
        })
        .catch(() => {});
    },
    //更新随机策略信息
    updateTacticsByTitleId(titleId) {
      getTacticsByTitleId(titleId).then((response) => {
        if (response.code === 200) {
          this.form.titleList.forEach((title) => {
            let tacticsList = response.data.filter(
              (item) => item.titleId === title.id
            );
            if (tacticsList.length > 0)
              this.$set(title, "tacticsList", tacticsList);
            else title.tacticsList = [];
          });
        }
      });
    },
    //关闭试题编辑页面
    topicEditClose(topicId, titleId) {
      getPaperTopic(topicId, titleId).then((res) => {
        this.form.titleList.forEach((title) => {
          if (title.id === titleId) {
            let index = title.topicList.findIndex(
              (topic) => topic.id === topicId
            );
            if (index >= 0) {
              title.topicList.splice(index, 1, res.data);
            } else {
              title.topicList.push(res.data);
            }
            title.topicNum = title.topicList.length;
            //试题列表累加分数计算大题分数
            title.score = title.topicList.reduce((total, topic) => {
              return total + topic.score;
            }, 0);
          }
        });
      });
      this.form.showTopicEdit = false;
      this.sortTitleList();
    },
    //关闭试题编辑页面
    topicEditCancel() {
      this.form.showTopicEdit = false;
    },
    /**点击批量修改分数按钮输入框获取焦点 */
    editAvgScore(titleId) {
      this.$nextTick(() => {
        this.$refs["avgScoreVal$" + titleId][0].focus();
      });
    },
    /**返回题型 */
    returnTopicType(type) {
      return this.dict.type.topic_type.find((item) => item.value === type + "")
        .label;
    },
    /**返回难度 */
    returnDifficulty(difficulty) {
      return this.dict.type.topic_difficulty.find(
        (item) => item.value === difficulty + ""
      ).label;
    },
    /**titleList重新排序跟生成序号 */
    sortTitleList() {
      let topicIndex = 1;
      this.form.titleList.sort((a, b) => {
        return a.sort - b.sort;
      });
      this.form.titleList.forEach((title, index) => {
        title.sort = index + 1;
        if (title.type === 1 && title.topicList) {
          title.topicList.forEach((topic) => {
            this.$set(topic, "index", topicIndex++);
          });
        } else if (
          title.type === 2 &&
          title.containerList &&
          title.containerList.length > 0
        ) {
          let topicNum = title.containerList
            .concat()
            .map((item) => item.extractNum)
            .reduce((total, num) => total + num);
          let score = title.containerList
            .concat()
            .map((item) => item.score * item.extractNum)
            .reduce((total, num) => total + num);
          this.$set(title, "topicNum", topicNum);
          this.$set(title, "score", score);
          title.containerList.forEach((container) => {
            if (container.extractNum > 0) {
              const start = topicIndex;
              let end = topicIndex + container.extractNum - 1;
              topicIndex = end + 1;
              if (start === end) this.$set(container, "index", start);
              else this.$set(container, "index", start + "~" + end);
            }
          });
        } else if (
          title.type === 3 &&
          title.tacticsList &&
          title.tacticsList.length > 0
        ) {
          let totalTopicNum = title.tacticsList
            .concat()
            .map((item) => item.extractNum)
            .reduce((total, num) => total + num);
          let totalScore = title.tacticsList
            .concat()
            .map((item) => item.score * item.extractNum)
            .reduce((total, num) => total + num);
          this.$set(title, "topicNum", totalTopicNum);
          this.$set(title, "score", totalScore);
          title.tacticsList.forEach((tactics) => {
            if (tactics.extractNum > 0) {
              const start = topicIndex;
              let end = topicIndex + tactics.extractNum - 1;
              topicIndex = end + 1;
              if (start === end) this.$set(tactics, "index", start);
              else this.$set(tactics, "index", start + "~" + end);
            }
          });
        }
      });
    },
    /**批量修改分数 */
    setScore(title) {
      setTitleAvgScore(title.id, title.type, title.avgScore).then((res) => {
        if (res.code === 200) {
          this.form.titleList.forEach((item) => {
            if (item.id === title.id) {
              if (item.type === 1)
                item.topicList.forEach((topic) => {
                  this.$set(topic, "score", title.avgScore);
                });
              else if (item.type === 2)
                item.containerList.forEach((container) => {
                  this.$set(container, "score", title.avgScore);
                });
              else
                item.tacticsList.forEach((tactics) => {
                  this.$set(tactics, "score", title.avgScore);
                });
              item.score = item.topicNum * title.avgScore;
            }
          });
        } else {
          this.$modal.msgError(res.msg);
        }
      });
    },
    /**删除title */
    delBigTitle(title, index) {
      this.form.titleList.splice(index, 1);
      this.sortTitleList();
      removePaperTitle(title.id).then((res) => {
        if (res.code === 200) {
          this.$modal.msgSuccess("删除成功");
        } else {
          this.$modal.msgError("删除失败:" + res.msg);
        }
      });
    },
    /**移动title */
    moveTitle(id, sort, type) {
      this.form.titleList.forEach((title) => {
        if (title.id === id) {
          title.sort = sort + type;
        } else if (title.sort === sort + type) {
          title.sort = sort;
        }
      });
      sortPaperTitle(id, type);
      this.sortTitleList();
    },

    /**添加大题 */
    addBigTitle(type) {
      const loading = this.$loading({
        lock: true,
        text: "正在添加…",
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.6)",
      });
      let bigTitle = {
        type: type,
        title: "第" + (this.form.titleList.length + 1) + "大题",
        topicList: [],
        containerList: [],
        tacticsList: [],
        examId: this.form.paper.id,
        topicNum: 0,
        score: 0,
        sort: this.form.titleList.length + 1,
        editTitle: false,
      };
      addPaperTitle(bigTitle)
        .then((res) => {
          bigTitle.id = res.data;
          this.form.titleList.push(bigTitle);
          loading.close();
        })
        .catch(() => {
          loading.close();
        });
    },

    /**获取知识点树 */
    refreshTopicCategoryTree() {
      if (this.topicCategoryId) {
        getTopicCategoryTree(this.topicCategoryId).then((response) => {
          this.$nextTick(() => {
            this.topicCategoryTree = response.data;
          });
        });
      }
    },
    /** 修改试题分数 */
    changeTopicScore(topicId, titleId, score) {
      console.log(score, "score");
      if (!score) {
        this.$modal.msgWarning("分数不能为空且大于0");
        return;
      }
      changeTopicScore(topicId, titleId, score).then((response) => {
        if (response.code === 200) {
          let index = this.form.titleList.findIndex(
            (item) => item.id === titleId
          );
          let bigTitle = this.form.titleList[index];
          let totalScore = 0;
          bigTitle.topicList.forEach((item) => {
            totalScore += Number(item.score);
          });
          bigTitle.score = totalScore;
          this.$set(this.form.titleList, index, bigTitle);
          let titleLabel = this.topicLabelList[index];
          titleLabel.score = totalScore;
          this.$set(this.topicLabelList, index, titleLabel);

          this.$modal.msgSuccess("修改成功");
        } else this.$modal.msgError("修改失败:" + response.msg);
      });
    },
    /** 修改试题 */
    showTopicEditDialog(topicId, titleId) {
      this.form.showTopicEdit = true;
      if (topicId === 0) {
        this.$nextTick(() => {
          this.form.topicEditTitle = "新增试题";
          this.$refs.myTopicForm.reset(titleId, 0);
        });
      } else {
        this.$nextTick(() => {
          this.form.topicEditTitle = "修改试题";
          this.$refs.myTopicForm.getTopicInfo(topicId, titleId, 0);
        });
      }
    },
    /**勾选添加试题 */
    showTopicListDialog(titleId) {
      this.form.showTopicList = true;
      this.$nextTick(() => {
        this.$refs.myTopicList.loadTopicList(titleId, 0, this.operationType);
      });
    },
    /** 修改抽题容器 */
    showContainerEditDialog(containerId, titleId) {
      this.form.showContainerEdit = true;
      this.openContainerId = containerId;
      this.openContainerTitleId = titleId;
      if (containerId === 0) {
        this.$nextTick(() => {
          this.form.containerEditTitle = "新增抽题容器";
          this.$refs.myContainerEdit.reset(titleId);
        });
      } else {
        this.$nextTick(() => {
          this.form.containerEditTitle = "修改抽题容器";
          this.$refs.myContainerEdit.getList(containerId, titleId);
        });
      }
    },
    /** 关闭抽题容器页面 */
    closeContainerDialog() {
      getContainerById(this.openContainerId).then((response) => {
        if (response.code === 200) {
          this.form.titleList.forEach((title) => {
            if (title.id === this.openContainerTitleId) {
              let index = title.containerList.findIndex(
                (item) => item.id === this.openContainerId
              );
              title.containerList.splice(index, 1, response.data);
            }
          });
          this.updateTacticsByTitleId(this.openContainerTitleId);
          this.$nextTick(() => {
            this.sortTitleList();
          });
        }
      });
    },
    /**保存试卷信息 */
    submitForm(type) {
      if (type === 0) this.$modal.msgSuccess("修改成功");
    },
    /**抽题容器不限难度数量修改 */
    containerUnlimitedNumChange(row) {
      if (row.unlimitedNum > row.optionalUnlimitedNum) {
        this.$modal.msgWarning("抽题数量不能大于可选数量");
        this.$set(row, "unlimitedNum", row.optionalUnlimitedNum);
      } else if (row.unlimitedNum < 0) {
        this.$modal.msgWarning("抽题数量不能小于0");
        this.$set(row, "unlimitedNum", 0);
      }
      updateContainerUnlimitedNum(row.id, row.unlimitedNum).then((response) => {
        if (response.code != 200) {
          this.$modal.msgError("修改失败:" + response.msg);
        }
      });
      this.updateExtractNum(row);
    },
    /**抽题容器简单数量修改 */
    containerEasyNumChange(row) {
      if (row.easyNum > row.optionalEasyNum) {
        this.$modal.msgWarning("抽题数量不能大于可选数量");
        this.$set(row, "easyNum", row.optionalEasyNum);
      } else if (row.easyNum < 0) {
        this.$modal.msgWarning("抽题数量不能小于0");
        this.$set(row, "easyNum", 0);
      }
      updateContainerEasyNum(row.id, row.easyNum).then((response) => {
        if (response.code != 200) {
          this.$modal.msgError("修改失败:" + response.msg);
        }
      });
      this.updateExtractNum(row);
    },
    /**抽题容器普通数量修改 */
    containerNormalNumChange(row) {
      if (row.normalNum > row.optionalNormalNum) {
        this.$modal.msgWarning("抽题数量不能大于可选数量");
        this.$set(row, "normalNum", row.optionalNormalNum);
      } else if (row.normalNum < 0) {
        this.$modal.msgWarning("抽题数量不能小于0");
        this.$set(row, "normalNum", 0);
      }
      updateContainerNormalNum(row.id, row.normalNum).then((response) => {
        if (response.code != 200) {
          this.$modal.msgError("修改失败:" + response.msg);
        }
      });
      this.updateExtractNum(row);
    },
    /**抽题容器困难数量修改 */
    containerHardNumChange(row) {
      if (row.hardNum > row.optionalHardNum) {
        this.$modal.msgWarning("抽题数量不能大于可选数量");
        this.$set(row, "hardNum", row.optionalHardNum);
      } else if (row.hardNum < 0) {
        this.$modal.msgWarning("抽题数量不能小于0");
        this.$set(row, "hardNum", 0);
      }
      updateContainerHardNum(row.id, row.hardNum).then((response) => {
        if (response.code != 200) {
          this.$modal.msgError("修改失败:" + response.msg);
        }
      });
      this.updateExtractNum(row);
    },
    /**抽题容器分数修改 */
    containerScoreChange(row) {
      if (!row.score) {
        this.$modal.msgWarning("分数不能为空且不能小于0");
        return;
      }
      updateContainerScore(row.id, row.score).then((response) => {
        if (response.code != 200) {
          this.$modal.msgError("修改失败:" + response.msg);
        } else {
          this.$modal.msgSuccess("修改成功");
        }
      });
      this.updateExtractNum(row);
    },
    /**随机策略不限难度数量修改 */
    tacticsUnlimitedNumChange(row) {
      if (row.unlimitedNum > row.optionalUnlimitedNum) {
        this.$modal.msgWarning("抽题数量不能大于可选数量");
        this.$set(row, "unlimitedNum", row.optionalUnlimitedNum);
      } else if (row.unlimitedNum < 0) {
        this.$modal.msgWarning("抽题数量不能小于0");
        this.$set(row, "unlimitedNum", 0);
      }
      updateTacticsUnlimitedNum(row.id, row.unlimitedNum).then((response) => {
        if (response.code != 200) {
          this.$modal.msgError("修改失败:" + response.msg);
        }
      });
      this.updateExtractNum(row);
    },
    /**随机策略简单数量修改 */
    tacticsEasyNumChange(row) {
      if (row.easyNum > row.optionalEasyNum) {
        this.$modal.msgWarning("抽题数量不能大于可选数量");
        this.$set(row, "easyNum", row.optionalEasyNum);
      } else if (row.easyNum < 0) {
        this.$modal.msgWarning("抽题数量不能小于0");
        this.$set(row, "easyNum", 0);
      }
      updateTacticsEasyNum(row.id, row.easyNum).then((response) => {
        if (response.code != 200) {
          this.$modal.msgError("修改失败:" + response.msg);
        }
      });
      this.updateExtractNum(row);
    },
    /**随机策略普通数量修改 */
    tacticsNormalNumChange(row) {
      if (row.normalNum > row.optionalNormalNum) {
        this.$modal.msgWarning("抽题数量不能大于可选数量");
        this.$set(row, "normalNum", row.optionalNormalNum);
      } else if (row.normalNum < 0) {
        this.$modal.msgWarning("抽题数量不能小于0");
        this.$set(row, "normalNum", 0);
      }
      updateTacticsNormalNum(row.id, row.normalNum).then((response) => {
        if (response.code != 200) {
          this.$modal.msgError("修改失败:" + response.msg);
        }
      });
      this.updateExtractNum(row);
    },
    /**随机策略困难数量修改 */
    tacticsHardNumChange(row) {
      if (row.hardNum > row.optionalHardNum) {
        this.$modal.msgWarning("抽题数量不能大于可选数量");
        this.$set(row, "hardNum", row.optionalHardNum);
      } else if (row.hardNum < 0) {
        this.$modal.msgWarning("抽题数量不能小于0");
        this.$set(row, "hardNum", 0);
      }
      updateTacticsHardNum(row.id, row.hardNum).then((response) => {
        if (response.code != 200) {
          this.$modal.msgError("修改失败:" + response.msg);
        }
      });
      this.updateExtractNum(row);
    },
    /**随机策略分数修改 */
    tacticsScoreChange(row) {
      if (!row.score) {
        this.$modal.msgWarning("分数不能为空且不能小于0");
        return;
      }
      updateTacticsScore(row.id, row.score).then((response) => {
        if (response.code != 200) {
          this.$modal.msgError("修改失败:" + response.msg);
        } else {
          this.$modal.msgSuccess("修改成功");
        }
      });
      this.updateExtractNum(row);
    },
    /**更新抽取数量 */
    updateExtractNum(row) {
      this.$set(
        row,
        "extractNum",
        Number(row.easyNum) +
          Number(row.normalNum) +
          Number(row.hardNum) +
          Number(row.unlimitedNum)
      );
      this.form.titleList.forEach((title) => {
        if (title.type === 2 && title.containerList) {
          let extractNum = 0;
          let score = 0;
          title.containerList.forEach((container) => {
            extractNum += container.extractNum;
            score += container.score * container.extractNum;
          });
          this.$set(title, "topicNum", extractNum);
          this.$set(title, "score", score);
        } else if (title.type === 3 && title.tacticsList) {
          let extractNum = 0;
          let score = 0;
          title.tacticsList.forEach((tactics) => {
            extractNum += tactics.extractNum;
            score += tactics.score * tactics.extractNum;
          });
          this.$set(title, "topicNum", extractNum);
          this.$set(title, "score", score);
        }
      });
      this.sortTitleList();
    },
    /** 随机策略修改分类 */
    topicCategoryChange(tactics) {
      let value = tactics.categoryId;
      if (value == null || value == undefined || value.length == 0) {
        return;
      }
      let categoryId = value[value.length - 1];
      tactics.categoryId = categoryId;
      this.updateTacticsInfo(tactics);
    },
    /**随机策略修改题型 */
    updateTacticsInfo(tactics) {
      if (
        tactics.categoryId == null ||
        tactics.categoryId == undefined ||
        tactics.topicType == null ||
        tactics.topicType == undefined
      ) {
        return;
      }
      updateTacticsInfo(tactics.id, tactics.categoryId, tactics.topicType).then(
        (response) => {
          if (response.code == 200) {
            this.form.titleList.forEach((title) => {
              if (title.id === tactics.titleId) {
                let index = title.tacticsList.findIndex(
                  (item) => item.id === tactics.id
                );
                title.tacticsList.splice(index, 1, response.data);
              }
            });
            this.updateExtractNum(tactics);
          } else this.$modal.msgError("修改失败:" + response.msg);
        }
      );
    },
  },
  watch: {
    examDialogOpen: {
      handler(val) {
        if (val) {
          console.log("paperDia_topicCategoryId", val, this.topicCategoryId);
          this.refreshTopicCategoryTree();
        }
      },
      immediate: true,
    },
    topicCategoryId(e) {
    },
    topicLabelList: {
      deep: true,
      immediate: true,
      handler(val) {
        let totalScore = 0;
        let totalTopicNum = 0;
        val.forEach((title) => {
          totalScore += title.score;
          totalTopicNum += title.topicNum;
        });
        this.totalScore = totalScore;
        this.totalTopicNum = totalTopicNum;
      },
    },
    "form.titleList": {
      handler: function (newVal, oldVal) {
        console.log(newVal, "newVal");
        console.log(oldVal, "oldVal");
        if (newVal == null || newVal == undefined) {
          return;
        }
        this.topicLabelList = [];
        let index = 1;
        if (newVal) {
          newVal.forEach((title) => {
            let titleParam = {
              id: title.id,
              sort: title.sort,
              title: title.title,
              topicNum: title.topicNum,
              score: title.score,
              labelList: [],
              edit: false,
              delState: false,
              avgScore: 0,
              type: title.type,
            };
            if (title.type === 1 && title.topicList) {
              title.topicList.forEach((topic) => {
                titleParam.labelList.push({
                  id: "topic-" + topic.id,
                  index: index++,
                });
              });
            } else if (
              title.type === 2 &&
              title.containerList &&
              title.containerList.length > 0
            ) {
              title.containerList.forEach((container) => {
                for (let i = 0; i < container.extractNum; i++) {
                  titleParam.labelList.push({
                    id: "container-" + container.id,
                    index: index++,
                  });
                }
              });
            } else if (title.type === 3 && title.tacticsList) {
              title.tacticsList.forEach((tactics) => {
                for (let i = 0; i < tactics.extractNum; i++) {
                  titleParam.labelList.push({
                    id: "tactics-" + tactics.id,
                    index: index++,
                  });
                }
              });
            }
            this.topicLabelList.push(titleParam);
          });
        }
        this.$emit("getTotalScore", this.getTotalScore());
        // this.refreshTopicCategoryTree();
      },
      deep: true,
      // immediate: true,
    },
  },
};
</script>

<style scoped lang="scss">
.container {
  width: 100%;
  height: 100%;
  padding: 0 10px;
  box-sizing: border-box;
  display: flex;
  align-items: flex-start;
  &_left {
    width: 320px;
    height: 100%;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
    border-radius: 15px;
    .title_total {
      width: 100%;
      padding: 10px;
      background: white;
      border-bottom: 1px solid rgba(0, 0, 0, 0.12);
      span {
        font-weight: bold;
        margin: 0 4px;
        font-size: 18px;
      }
    }
    .title_card {
      width: 100%;
      padding: 10px;
      box-sizing: border-box;
      height: calc(100vh - 480px);
      overflow: auto;
      .box_card {
        width: 100%;
        .topicBox {
          width: 100%;
          display: flex;
          flex-wrap: wrap;
          align-items: flex-start;
          .label_index {
            cursor: pointer;
            user-select: none;
            margin: 0 0 10px 10px;
            width: 36px;
            height: 36px;
            background: #ffffff;
            color: #999999;
            border-radius: 50%;
            border: 1px solid #28b28b;
            display: flex;
            justify-content: center;
            align-items: center;
          }
        }
      }
    }
    .title_card::-webkit-scrollbar {
      display: none;
    }
    .title_card:hover {
      &::-webkit-scrollbar {
        display: block;
      }
    }
  }
  &_right {
    height: 100%;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
    overflow: auto;
    border-radius: 15px;
    flex: 1;
    margin-left: 20px;
    .el-card:first-child {
      border-radius: 15px 15px 0 0;
    }
    .el-card:last-child {
      border-radius: 0 0 15px 15px;
    }
  }
  &_right::-webkit-scrollbar {
    display: none;
  }
}
.add_topic_btn {
  width: calc(100% + 2px);
  margin-left: -1px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  background: #1ab394;
  cursor: pointer;
  user-select: none;
  position: relative;
  color: white;
  border-radius: 15px 15px 0 0;
  font-weight: bold;
  .el-icon-caret-right {
    position: absolute;
    right: 20px;
  }
}
.add_topic_btn:active {
  margin-left: 0;
  width: 100%;
  border: 0;
}
.topic_type {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 170px;
  .topic_item {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 60px;
    cursor: pointer;
    user-select: none;
    border-bottom: 1px solid #ebeef5;
    font-size: 16px;
  }
  .topic_item:hover {
    color: #1ab394 !important;
  }
}

::v-deep .error_border .el-input__inner {
  border: 1px solid red !important;
}

::v-deep .errors_border .el-input__inner {
  border: 1px solid red !important;
}
</style>
